package com.frogs.ucenter.service.daoimpl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.frogs.framework.base.dao.BaseDao;
import com.frogs.framework.base.service.daoimpl.BaseServiceImpl;
import com.frogs.framework.util.StringUtil;
import com.frogs.system.util.UserRechargeableCardStatusEnum;
import com.frogs.ucenter.dao.UserRechargeableCardDao;
import com.frogs.ucenter.entity.UserRechargeableCard;
import com.frogs.ucenter.service.UserRechargeableCardService;
import com.frogs.ucenter.util.Constants;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
@Service("userRechargeableCardService")
public class UserRechargeableCardServiceImpl extends BaseServiceImpl<UserRechargeableCard> implements UserRechargeableCardService {
   
	private static final Logger log = LoggerFactory.getLogger(UserRechargeableCardServiceImpl.class);
	
	@Autowired
    private UserRechargeableCardDao userRechargeableCardDao;

    public UserRechargeableCardServiceImpl() {
        super();
    }

    public UserRechargeableCardDao getUserRechargeableCardDao() {
        return userRechargeableCardDao;
    }

    /**
     * Don't remove or edit it.
     */
    @Override
    protected BaseDao<UserRechargeableCard> getBaseDao() {
        return userRechargeableCardDao;
    }

    public void setUserRechargeableCardDao(UserRechargeableCardDao userRechargeableCardDao) {
        this.userRechargeableCardDao = userRechargeableCardDao;
    }

	/* (non-Javadoc)
	 * 导入excel数据
	 */
	@Override
	public Map<String,Object> excelDeal(String fileName) {
		Map<String, Object> map = new HashMap<String, Object>();
		InputStream inputStream = null ;
		try{
			inputStream = new FileInputStream(fileName);//获取临时文件流
		    Workbook book = (Workbook) WorkbookFactory.create(inputStream);//获取临时文件workbook
	        Sheet sheet = book.getSheetAt(0);//获取临时文件workbook的第一个sheet
			int rows = sheet.getLastRowNum();//获取临时文件workbook的第一个sheet的总条数
			List<UserRechargeableCard> cardList = new ArrayList<UserRechargeableCard>();
			String inRechargeCards = "";
			for(int i =1; i <=rows; i++) {
				Row row = sheet.getRow(i);
				String cardNo = "";
				String cardPassword = "";
				double money = 0.0;
	            if(row.getCell(0).getCellType() == Cell.CELL_TYPE_STRING){
	            	cardNo=row.getCell(0).getStringCellValue().trim();
	            }else if(row.getCell(0).getCellType() == Cell.CELL_TYPE_NUMERIC){
	            	cardNo = String.valueOf((int)(row.getCell(0).getNumericCellValue()));
	            }else{
	            	cardNo = "";
	            }
	            if(StringUtil.isEmpty(cardNo)){
	            	break;
	            }
	            if(row.getCell(1).getCellType() == Cell.CELL_TYPE_STRING){
	            	cardPassword=row.getCell(1).getStringCellValue().trim();
	            }else if(row.getCell(1).getCellType() == Cell.CELL_TYPE_NUMERIC){
	            	cardPassword = String.valueOf((int)(row.getCell(1).getNumericCellValue()));
	            }
	            if(row.getCell(2).getCellType() == Cell.CELL_TYPE_STRING){
	            	money = Double.parseDouble(row.getCell(2).getStringCellValue());
	            }else if(row.getCell(2).getCellType() == Cell.CELL_TYPE_NUMERIC){
	            	money = row.getCell(2).getNumericCellValue();
	            }
				inRechargeCards = cardNo + "," + inRechargeCards;
    			UserRechargeableCard card = new UserRechargeableCard();
    			card.setDenomination(new BigDecimal(money));
    			card.setRechargeCard(cardNo);
    			card.setCardPasswd(StringUtil.md5(cardNo + cardPassword, Constants.ENCRYPT_RECHARGEABLE_CARD_KEY));
    			card.setStatus(UserRechargeableCardStatusEnum.UNUSED.getId());
    			cardList.add(card);
			}
			if(inRechargeCards.trim().length()>0){
				inRechargeCards = inRechargeCards.substring(0, inRechargeCards.length()-1);
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("inRechargeCards", inRechargeCards);
				if(userRechargeableCardDao.selectCountByMap(params)>0){
					map.put("code", 0);
					map.put("msg", "存在重复的数据，请检查数据的合法性");
				}else{
					userRechargeableCardDao.batchInsert(cardList);
					map.put("code", 1);
					map.put("msg", "数据导入成功");
					map.put("cardList", cardList);
				}
			}else{
				map.put("code", 0);
				map.put("msg", "导入数据为空，请导入数据");
			}
			inputStream.close();
		}catch(Exception e){
			map.put("code", 0);
			map.put("msg", "导入数据有误");
			log.error("func[excelDeal] fileName[" + fileName + "] error[" + e.getMessage() + "]", e);
		}finally {
			File srcFile = new File(fileName);
			if(srcFile.exists()){
				try {
					inputStream.close();
					if (!srcFile.delete()) { 
						log.error("删除文件失败");
					}
				} catch (IOException e) {
					log.error("func[excelDeal] fileName[" + fileName + "] IOException error[" + e.getMessage() + "]", e);
				}

			}
		}
		return map;
	}

	@Override
	public void updateByStatus(Map<String, Object> param) {
		userRechargeableCardDao.updateByMap(param);
	}
}